<?php
namespace app\models;
/**
 * @desc 出库单
 */

use app\models\BaseModel;
use app\enum\EnumOther;
use app\dao\OutstoreDAO;
use app\dao\OutstoreDetailDAO;
use app\dao\TransactionDAO;
use app\dao\ProductDAO;
use Yii;
use app\dao\StockPileDAO;
use app\helpers\Utility;
use app\enum\EnumOriginType;
use app\dao\ProductUpdateLogDAO;
use app\dao\WarehouseDAO;

class OutstoreModel extends BaseModel
{
	/**
	 * @desc 覆盖父方法返回对象
	 * @author liaojianwen
	 * @date 2016-11-29
	 * @return OutstoreModel
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
	
	/**
	 * @desc 保存出库单
	 * @param [] $head 出库单头
	 * @param [] $detail 出库单明细
	 * @param $id //出库单id //有就是编辑,没有就是新增
	 * @param $remove 删除的明细
	 * @author liaojianwen
	 * @date 2016-11-29
	 */
	public function saveOutstore($head, $detail,$remove,$id)
	{
		if(empty($head)){
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'head is empty' );
		}
		if (empty ( $detail )) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'detail is empty' );
		}
		
		//清掉为空的元素
		foreach ($head as $k =>$hed){
			if(empty($hed)){
				unset($head[$k]);
			}
		}
		foreach ($detail as $k=> $det){
			foreach ($det as $j => $deet){
				if(empty($deet)){
					unset($detail[$k][$j]);
				}
			}
		}
		
		// 表头信息
		$head ['outstore_date'] = strtotime ( $head ['outstore_date'] );
		$cond_head = "outstore_id =:id || outstore_no =:no";
		$param_head = [ 
				':id' => $id ,
				':no'=>$head['outstore_no'],
		];
	
		$Iid = OutstoreDAO::getInstance ()->ireplaceinto ( $head, $cond_head, $param_head, true );
		if (! $Iid) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save outstore_head failure' );
		}
		// 表单明细

// 		OutstoreDetailDAO::getInstance()->iupdate(['delete_flag' => EnumOther::DELETED], "outstore_id =:did", [':did'=>$Iid]);// 先删除后没有删除的数据更新回来
		//删除的明细
		foreach ($remove as $move){
			$res_remove = OutstoreDetailDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "outstore_det_id = :det_id", [':det_id'=>$move['outstore_det_id']]);
			if(!$res_remove){
				$tr->rollBack();
				$this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'remove outstore_det_id:'+$move['outstore_det_id'] +'failed');
			}
		}
		foreach ( $detail as &$det ) {
			$det ['outstore_id'] = $Iid;
			$det ['delete_flag'] = EnumOther::NO_DELETE;
			$cond_det = "outstore_id = :id and outstore_det_id = :lid";
			$param_det = [ 
					':id' => $Iid,
					':lid' => isset($det ['outstore_det_id'])?$det['outstore_det_id']:0,
			];

			$res_det = OutstoreDetailDAO::getInstance ()->ireplaceinto ( $det, $cond_det, $param_det, true );
			if (! $res_det) {
				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save outstore_detail failure' );
			}
		}
		
		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
	}
	
	/**
	 * @desc 获取出库单列表数据
	 * @param [] $pageInfo
	 * @param [] $condition //查询条件
	 * @author liaojianwen
	 * @date 2016-11-29
	 */
	public function getOutstores($pageInfo, $condition, $filter)
	{
		if(empty($pageInfo)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
		}
		$result = OutstoreDAO::getInstance()->getOutstores($condition, $filter, $pageInfo);
		if(empty($result)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
		}
		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
	}
	
	/**
	 * @desc 根据id 获取出库单信息
	 * @param int $id //出库单id
	 * @author liaojianwen
	 * @date 2016-11-29
	 */
	public function getOutstoreInfo($id)
	{
		if(empty($id)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
		}
		$out_head = OutstoreDAO::getInstance()->getOutstoreHead($id);
		if(empty($out_head)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','head data found');
		}
		$out_det = OutstoreDetailDAO::getInstance()->getOutstoreDet($id);
		if(empty($out_det)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','detail data found');
		}
		$result['head'] = $out_head;
		$result['det'] = $out_det;
		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
	}
	
	/**
	 * @desc 确认入库单
	 * @author liaojianwen
	 * @date 2016-11-25
	 */
	public function confirmOutstore($id)
	{
		if (! $id) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
		}
		$id = (int)$id;
		$tr = Yii::$app->db->beginTransaction ();
		try {
			$re_confirm = OutstoreDAO::getInstance ()->updateByPk ( $id, [
					'confirm_flag' => EnumOther::CONFIRM
			] );
			if (! $re_confirm) {
				$tr->rollBack ();
				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'confirm fail' );
			}
			$fields = [
					'h.outstore_no',
					'd.goods_id',
					'd.quantity',
					'h.outstore_type',
					'd.outstore_det_id',
					'h.warehouse_id',
					'h.outstore_date',
					'd.unit',
					'd.base_quantity',
					'd.base_unit',
					's.quantity squantity',
			];
			$conditions = "d.outstore_id =:id and d.delete_flag = :flag";
			$params = [
					':id' => $id,
					':flag' => EnumOther::NO_DELETE
			];
			$joinArray = [
					[
							'outstore h',
							"h.outstore_id = d.outstore_id"
					],
					[
							'stock_pile s',
							's.product_id = d.goods_id and s.warehouse_id = h.warehouse_id'
					]
			];
			$instore_det = OutstoreDetailDAO::getInstance ()->iselect ( $fields, $conditions, $params, 'all', 'd.outstore_det_id ASC', $joinArray, 'd' );
			if (! $instore_det) {
				$tr->rollBack ();
				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'select det fail' );
			}
			// 出库明细
			foreach ( $instore_det as $det ) {
				
				$PRODUCT = ProductDAO::getInstance()->iselect(["price","quantity","product_name"], "product_id = :pid", [':pid'=>$det['goods_id']],'one');
				if(isset($PRODUCT['price'])){
					$price = $PRODUCT['price'];
				} else {
					$price = 0;
				}
				
				if($det['base_quantity'] > $det['squantity']) {
					$tr->rollBack();
					return $this->handleApiFormat(EnumOther::ACK_FAILURE,$PRODUCT['product_name'],'overflow quantity');
				}
				$column_trans = array (
						'goods_id' => $det ['goods_id'],
						'quantity' => $det ['base_quantity'],
						'quantity_unit'=> $det['base_unit'],
						'origin_type' => $det ['outstore_type'],
						'origin_id' => $det ['outstore_no'],
						'origin_line_id' => $det ['outstore_det_id'], // 原单序号
						'origin_time'=>$det['outstore_date'],
						'warehouse_id' => $det ['warehouse_id'],
						'init_num' => $PRODUCT['quantity'],//上期数量
						'flag' => EnumOther::OUT_FLAG
				);
	
				$res_trans = TransactionDAO::getInstance ()->iinsert ( $column_trans, true );
				if (! $res_trans) {
					$tr->rollBack ();
					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save transaction failure' );
				}
				
				

				// 更新product quantity 减库存
				$WAREHOUSE = WarehouseDAO::getInstance()->iselect("is_scrapped,warehouse_name", "warehouse_id =:wid", [':wid'=>$det['warehouse_id']],'one');
				if(isset($WAREHOUSE['is_scrapped'])){
					if($WAREHOUSE['is_scrapped'] != '1'){//不是报废单
						$pro_select = ProductDAO::getInstance ()->updateAllCounters ( [
								'quantity' => - $det ['base_quantity'],
								'amount' => -($det['base_quantity'] * $price)
						], "product_id =:id", [
								':id' => $det ['goods_id']
						] );
						if (! $pro_select) {
							$tr->rollBack ();
							return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'update product quantity failure' );
						}
					}
				} else {
					$tr->rollBack();
					return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','select scrapped failed');
				}
			
				//product_update_log 商品更新记录
				$_order_type = Utility::getArrayValue(EnumOriginType::$origin_type, $det['outstore_type']);
				
				$log_columns = [
						'product_id' => $det ['goods_id'],
						'update_num' => $det ['base_quantity'],
						'num_unit' => $det['base_unit'],
						'origin_id' => $id,
						'origin_no' => $det['outstore_no'],
						'origin_line_id'=> $det['outstore_det_id'],
						'origin_type'=> $det['outstore_type'],
						'update_time'=>strtotime(date('Y-m-d')),
						'flag'=> EnumOther::OUT_FLAG,
						'initial_num'=> $PRODUCT['quantity'],//上期数量
						'remark'=> $_order_type .($WAREHOUSE['warehouse_name']?:''). EnumOther::MINUS,
						'warehouse_id' => $det['warehouse_id'],
						'create_man' => Yii::$app->user->id,
				];
				$res_log = ProductUpdateLogDAO::getInstance()->iinsert($log_columns, true);
				if(! $res_log){
					$tr->rollBack();
					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'product update log failure');
				}
				
				
				//分仓列表数据的插入或者更新--start
				$stock_conditions = "warehouse_id =:wid and product_id=:pid and delete_flag =:flag";
				$stock_params = [
						':wid'=>$det['warehouse_id'],
						':pid'=>$det['goods_id'],
						':flag'=> EnumOther::NO_DELETE,
				];
				$stock_select = StockPileDAO::getInstance()->iselect("stock_pile_id", $stock_conditions, $stock_params,'one');
				if(! $stock_select){
					//没有数据，插入新数据
// 					$stock_columns = [
// 							'warehouse_id'=> $det['warehouse_id'],
// 							'product_id'=> $det['goods_id'],
// 							'quantity'=> $det['quantity'],
// 							'quantity_unit'=> $det['unit'],
// 					];
// 					$stock_insert = StockPileDAO::getInstance()->iinsert($stock_columns, true);
// 					if(! $stock_insert){
						$tr->rollBack ();
						return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'select stock pile failure' );
// 					}
				} else {
					//有数据，更新数据
					$stock_update = StockPileDAO::getInstance()->updateAllCounters(['quantity'=> -$det['base_quantity']], $stock_conditions, $stock_params);
					if(! $stock_update){
						$tr->rollBack();
						return $this->handleApiFormat(EnumOther::ACK_FAILURE, '','update stock pile failure');
					}
				}
				//分仓 --end
	
			}
			$tr->commit();
			return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
		} catch ( \Exception $e ) {
			$tr->rollBack ();
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'', $e->getMessage());
		}
	}
	
	/**
	 * @desc 删除入库单
	 * @author liaojianwen
	 * @date 2016-11-28
	 */
	public function delOutstore($ids)
	{
		if(empty($ids)){
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
		}
		$_ids = explode ( ',', $ids );
	
		$tT = Yii::$app->db->beginTransaction ();
		try {
			foreach ( $_ids as $id ) {
				$res_outstore = OutstoreDAO::getInstance ()->updateByPk ( $id, ['delete_flag' => EnumOther::DELETED] );
				if(!$res_outstore){
					$tT->rollBack();
					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'del_outstore fail');
				}
				//instore_detail
				$outstore_det = OutstoreDetailDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "outstore_id=:id", [':id'=>$id]);
				if(!$outstore_det){
					$tT->rollBack();
					return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','del_outstore_det fail');
				}
				//更新product_quantity
				$fields = [
						't.goods_id',
						't.quantity',
						't.transaction_id',
						'd.unit',
						'o.warehouse_id',
						'o.outstore_no',
						'd.quantity as dd',
						'd.outstore_det_id',
						'o.outstore_type'
				];
				$conditions = "t.delete_flag = :flag";
				$params = [
						':flag'=>EnumOther::NO_DELETE,
				];
				$joinArray = [ 
						[ 
								'outstore o',
								'o.outstore_no = t.origin_id and o.outstore_id = ' . $id,
								'right' => '' 
						],
						[ 
								'outstore_detail d',
								'd.outstore_det_id = t.origin_line_id',
								'left' => '' 
						] 
				];
				$trans_select = TransactionDAO::getInstance()->iselect($fields, $conditions, $params,'all',"t.create_time ASC",$joinArray,'t');
				if (! empty ( $trans_select )) {
					// 已确认的入库单才有transtions,加库存
					foreach ( $trans_select as $trans ) {
						//记录更新product 前的quantity
						$PRODUCT = ProductDAO::getInstance()->iselect("quantity", "product_id = :pid", [':pid'=>$trans['goods_id']],'one');
						//更新product quantity
						$pro_minus = ProductDAO::getInstance ()->updateAllCounters ( [
								'quantity' => $trans ['quantity'],
						], "product_id =:id", [
								':id' => $trans ['goods_id']
						] );
							
						if (! $pro_minus) {
							$tr->rollBack ();
							return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'update product quantity failure' );
						}
	
						//product_update_log 商品更新记录
						$_order_type = Utility::getArrayValue(EnumOriginType::$origin_type, $trans['outstore_type']);
						
						$log_columns = [
								'product_id' => $trans ['goods_id'],
								'update_num' => $trans ['quantity'],
								'num_unit' => $trans['unit'],
								'origin_id' => $id,
								'origin_no' => $trans['outstore_no'],
								'origin_line_id'=> $trans['outstore_det_id'],
								'origin_type'=> $trans['outstore_type'],
								'update_time'=>strtotime(date('Y-m-d')),
								'flag'=> EnumOther::IN_FLAG,
								'initial_num'=> $PRODUCT['quantity'],//上期数量
								'remark'=> $_order_type . EnumOther::PLUS.',出库单删除',
								'warehouse_id' => $trans['warehouse_id'],
								'create_man' => Yii::$app->user->id,
						];
						$res_log = ProductUpdateLogDAO::getInstance()->iinsert($log_columns, true);
						if(! $res_log){
							$tr->rollBack();
							return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'product update log failure');
						}
						
						//删除transaction 数据
						$columns = [
								'delete_flag'=>EnumOther::DELETED,
						];
						$conditions = "transaction_id = :tid";
						$params = [
								':tid'=>$trans['transaction_id'],
						];
						$trans_update = TransactionDAO::getInstance()->iupdate($columns, $conditions, $params);
	
						if(empty($trans_update)){
							$tT->rollBack();
							return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','tansaction del fail');
						}
						
						// 更新stock_file 分仓表信息
						$stock_minus = StockPileDAO::getInstance ()->updateAllCounters ( [
								'quantity' => $trans ['quantity']
						], "warehouse_id =:wid and product_id=:pid and delete_flag =:flag", [
								':wid' => $trans ['warehouse_id'],
								':pid' => $trans ['goods_id'],
								':flag' => EnumOther::NO_DELETE
						] );
						if(! $stock_minus){
							$tr->rollBack ();
							return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'update stock pile quantity failure');
						}
					}
				}

			}
			$tT->commit();
			return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
		} catch ( \Exception $e ) {
			$tT->rollBack ();
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', $e->getMessage());
		}
	}
	
	/**
	 * @desc 获取出库明细
	 * @author liaojianwen
	 * @date 2016-12-29
	 */
	public function getoutstoreDet($id)
	{
		if (! $id) {
			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
		}
		$fields = [
				'outstore_det_id',
				'd.outstore_id',
				'd.goods_id',
				'p.product_name',
				'p.product_sn',
				'd.quantity',
				'd.unit',
				'u.unit_name',
				'd.price',
				'd.amount',
				'd.remark',
		];
	
		$joinArr = [
				[
						"product p",
						"p.product_id = d.goods_id"
				],
				[
						"unit u",
						"u.unit_id = d.unit"
				]
		];
		$conditions = "d.outstore_id = :id and d.delete_flag = :dflag";
		$params = [
				':id' => $id,
				':dflag' => EnumOther::NO_DELETE,
		];
		$result = OutstoreDetailDAO::getInstance()->iselect($fields, $conditions, $params, 'all',"outstore_det_id ASC", $joinArr,'d');
		if(empty($result)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
		}
		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, $result);
	}
	
	
	/**
	 * @desc 获取其他出库汇总数据
	 * @author liaojianwen
	 * @date 2018-01-30
	 */
	public function getOutstoreSummary($pageInfo, $cond)
	{
		if(empty($pageInfo)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'pageInfo is empty');
		}
		if(!isset($cond['starTime']) || empty($cond['starTime'])){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'search params time is empty');
		}
		$cond['starTime'] = strtotime($cond['starTime']);
		$cond['endTime'] = strtotime($cond['endTime']);
		$result =OutstoreDetailDAO::getInstance()->getOutstoreSummary($cond, $pageInfo);
		if(!$result){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'no data found');
		}
		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, $result);
	}
}